package com.example.springboot.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.common.ResultCode;
import com.example.springboot.common.config.JwtTokenUtils;
import com.example.springboot.dao.AdminMapper;
import com.example.springboot.dao.GradeMapper;
import com.example.springboot.dao.UserMapper;
import com.example.springboot.domain.po.Account;
import com.example.springboot.domain.po.Admin;
import com.example.springboot.domain.po.Grade;
import com.example.springboot.domain.po.User;
import com.example.springboot.exception.CustomException;
import com.example.springboot.service.AdminService;
import com.example.springboot.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author：伐柯梦姝
 * @Package：com.example.springboot.service.Impl
 * @Project：springboot
 * @name：AdminServiceImpl
 * @Date：2025/2/3 22:39
 * @Filename：AdminServiceImpl
 * @for:
 */
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Resource
    private AdminMapper adminMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private GradeMapper gradeMapper;

    @Override
    public List<Admin> getAll() {
        List<Admin> list = lambdaQuery()
                .list();
        return list;
    }

    @Override
    public Admin adminLogin(Admin admin) {
        Admin admin1 = this.selectByNameAndPassword(admin.getUsername(), admin.getPassword());
        if (ObjectUtil.isNotEmpty(admin1)) {
            return admin1;
        } else {
            throw new CustomException(ResultCode.USER_ACCOUNT_ERROR);
        }
    }

    @Override
    public Admin findById(Integer id) {
        return this.getById(id);
    }

    @Override
    public Admin adminRegister(Admin admin) {
        //如果用户名为空，抛出异常
        String username = admin.getUsername();
        if (!ObjectUtil.isNotEmpty(username)){
            throw new CustomException(ResultCode.USERNAME_ISNULL_ERROR);
        }
        //插入前做用户名唯一性校验
        Admin admin1 = this.selectByUserName(username);
        if (ObjectUtil.isNotEmpty(admin1)){
            throw  new CustomException(ResultCode.USER_EXIST_ERROR);
        }
        //设置默认头像
        if (ObjectUtil.isEmpty(admin.getAvatar())) {
            admin.setAvatar("http://localhost:8081/files/1738921400311-微信图片_20240701092647.png");
        }
        if (ObjectUtil.isEmpty(admin.getPassword())) {
            admin.setPassword("asd");
        }
        admin.setRole(1);
        this.save(admin);
        return admin;

    }

    @Override
    public void deleteById(Integer id) {
        this.removeById(id);
    }

    @Override
    public void update(Admin admin) {
        //如果用户名为空，抛出异常
        String username = admin.getUsername();
        if (!ObjectUtil.isNotEmpty(username)){
            throw new CustomException(ResultCode.USERNAME_ISNULL_ERROR);
        }
        //插入前做用户名唯一性校验
        Admin admin1 = this.selectByUserName(username);
        //如果修改的用户名与当前正在用的用户名一致，不需要再做唯一性校验
        Admin admin2 = this.getById(admin.getId());
        if (admin2.getUsername().equals(username)){
            this.saveOrUpdate(admin);
        }else if (ObjectUtil.isNotEmpty(admin1)){
            throw  new CustomException(ResultCode.USER_EXIST_ERROR);
        }
        this.saveOrUpdate(admin);
    }

    @Override
    public PageInfo<Admin> findPage(Admin search, Integer pageNum, Integer pageSize) {
        Account user = JwtTokenUtils.getCurrentUser();
        if (ObjectUtil.isEmpty(user)) {
            throw new CustomException(ResultCode.USER_NOT_LOGIN);
        }
        // 开启分页 一定要在操作数据库方法的上面
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> all = this.findByCondition(search);

        return PageInfo.of(all);
    }

    @Transactional
    @Override
    public Admin adminRole(Admin admin) {
//        1.执行删除操作:在管理员表里删除这个用户
        Integer id = admin.getId(); //拿到用户的Id
        this.deleteById(id);

//        2.把这个管理的信息新增到用户表
        User user = BeanUtil.copyProperties(admin, User.class);
        user.setRole(2);
        user.setId(null);
        String gradeName = user.getGradeName();
        if (ObjectUtil.isEmpty(gradeName)) {//加入没有填写班级名，则默认设为软工一班
            user.setGradeId(11);
        }else {
            Grade grade = gradeMapper.selectByGradeName(gradeName);
            user.setGradeId(grade.getId());
        }
        QueryWrapper<User> wrapper = new QueryWrapper<User>()
                .eq("username", admin.getUsername());
        User user1 = userMapper.selectOne(wrapper);
        if (ObjectUtil.isNotEmpty(user1)){
            throw  new CustomException(ResultCode.USER_EXIST_ERROR);
        }
        userMapper.insert(user);
        return admin;
    }

    public List<Admin> findByCondition(Admin admin){
        QueryWrapper<Admin> wrapper = new QueryWrapper<Admin>()
                .like(admin != null && ObjectUtil.isNotEmpty(admin.getUsername()),"username", admin.getUsername());
        return adminMapper.selectList(wrapper);

    }

    public Admin selectByUserName(String username) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<Admin>()
                .eq("username", username);
        return adminMapper.selectOne(queryWrapper);
    }
    public Admin selectByNameAndPassword(String username, String password) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<Admin>()
                .eq("username", username)
                .eq("password", password);
        return adminMapper.selectOne(wrapper);
    }
}
